/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package info.erlbach_kirchberg.erzWoerterbuch.ServerData;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;

import android.media.MediaPlayer;
import android.util.Log;

/**
 *
 * @author Laschi
 */
public class DBConnector {
	
	private static String server = "http://www.erlbach-kirchberg.info/media/sprache/webservice/getErzWoerter.php";
	public static boolean played=true;
	
    public static void playFile(File cacheDir, String file){     
        try {
        	played = false;
            URL url = new URL(server+file);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            
            urlConnection.connect();
            
            InputStream inputStream = urlConnection.getInputStream();
            
            File temp = File.createTempFile("test", "mp3", cacheDir);
            temp.deleteOnExit();
            FileOutputStream fileOutput =new FileOutputStream(temp);
            
            int totalSize = urlConnection.getContentLength();
            
            int downloadedSize = 0;

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                    //add the data in the buffer to the file in the file output stream (the file on the sd card
                    fileOutput.write(buffer, 0, bufferLength);
                    //add up the size so we know how much is downloaded
                    downloadedSize += bufferLength;

            }
            
            if (downloadedSize > 0) {
	            //close the output stream when done
	            fileOutput.close();
	            FileInputStream fileInput =new FileInputStream(temp);
	            
	            MediaPlayer mediaPlayer = new  MediaPlayer();
	            mediaPlayer.setDataSource(fileInput.getFD());
	            mediaPlayer.setVolume(1.0f, 1.0f);
	            
	            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
					public void onPrepared(MediaPlayer mp) {
						mp.start();		
						played = true;
					}
	            });  
	            
	            mediaPlayer.prepare();
	            
	            fileInput.close();
            }
            temp.delete();

        } catch (IOException ex) {
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public static JSONArray getJSONfromURL(String url){
        String result = "";
        JSONArray jArray = null;

        result = getStringfromURL(url);
                
        //try parse the string to a JSON object
        if (!result.equals("")) {
	        try{
	            jArray = new JSONArray(result);
	        }catch(JSONException e){
	            Log.e("log_tag", "Error parsing data "+e.toString());
	        }
        }
    
        return jArray;
    }  
    
    public static String getStringfromURL(String url){
        InputStream is = null;
        String result = "";

        //http post
        try {
        	HttpParams httpParams = new BasicHttpParams();
        	HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
        	HttpConnectionParams.setSoTimeout(httpParams, 8000);
        	
            HttpClient httpclient = new DefaultHttpClient(httpParams);
            HttpPost httppost = new HttpPost(server+url);
            HttpResponse response = httpclient.execute(httppost);
            if (response != null) {
            	if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            		return "";
            	}
            
            	HttpEntity entity = response.getEntity();
            	is = entity.getContent();
            }
        } catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());        
            return "";
        }
        //convert response to string
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();
        }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
            return "";
        }
    
        return result;
    }      
}
